package com.metroinfo.servers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.util.Timer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.metroinfo.infrastructure.MainDataStructure;
import com.metroinfo.test.client.Sender;
import com.metroinfo.test.client.SimpleClient;
import com.metroinfo.workers.ChannelIO;
import com.metroinfo.workers.RequestServicer;

public class SelectorSimpleServer {

	ServerSocketChannel ssc;

	private static final int POOL_MULTIPLE = 4;

	static private int PORT = 8000;
	static private int BACKLOG = 1024;
	private int brojac = 0;
	private long vreme = 0;

	private final MainDataStructure mainDataStructure;

	public SelectorSimpleServer(int port) throws Exception {

		ssc = ServerSocketChannel.open();
		ssc.socket().setReuseAddress(true);
		ssc.socket().bind(new InetSocketAddress(port), BACKLOG);
		// ssc.socket().setSoTimeout(5000);
		mainDataStructure = new MainDataStructure();
	}

	public void runServer() throws Exception {

		ExecutorService xec = Executors.newFixedThreadPool(Runtime.getRuntime()
				.availableProcessors()
				* POOL_MULTIPLE);

		for (;;) {

			SocketChannel sc = ssc.accept();

			brojac++;
			if (brojac == 1)
				vreme = System.currentTimeMillis();

			if (brojac == 1000) {
				brojac = 0;
				System.out.println("Vreme="
						+ (System.currentTimeMillis() - vreme));
			}
			ChannelIO cio = ChannelIO.getInstance(sc, true);

			RequestServicer svc = new RequestServicer(cio, mainDataStructure);
			xec.execute(svc);
		}
	}

	static public void main(String args[]) throws Exception {

		SimpleServer simpleServer = new SimpleServer(8000);

		System.out.println("startovao se");
		simpleServer.runServer();

	}
}
